<template>
  <el-dialog
    v-el-drag-dialog
    title="瓶批导入"
    :visible.sync="visible"
    width="1000px"
    class="pingpiImport"
    @closed="closed"
  >
    <el-form :inline="true" :model="form" class="customerForm">
      <el-form-item label="瓶批单号:">
        <el-input v-model.trim="form.invenBillCode" placeholder="请输入" clearable @keyup.enter.native="onSubmit" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="onSubmit">确认</el-button>
        <el-button type="default" size="mini" @click="toSelecte">选择</el-button>
      </el-form-item>
    </el-form>
    <div v-if="fillingInfo.invenBillCode">
      <div class="item-title">提瓶充装明细：</div>
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content">
              <span>提瓶人：</span><span>{{ fillingInfo.withdrawUser }}</span><span style="color: red;">(用户)</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <span>用户类型：</span><span>{{ fillingInfo.csmType? formatColumnMap(customerTypeMap, 'value', fillingInfo.csmType, 'desc'):'' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <span>单据标签：</span>
              <el-select v-model="fillingLabel" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in fillingLabelList"
                  :key="item.value"
                  :label="item.keyName"
                  :value="item.keyVal"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="grid-content">
              <span>用户编号：</span><span>{{ fillingInfo.withdrawCode }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="grid-content">
              <span>联系电话：</span><span>{{ fillingInfo.csmRgPhone }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="add"><span class="item-title">提瓶充装人员信息：</span></div>
      <el-table
        :data="fillingData"
        :summary-method="getSummaries"
        show-summary
        class="fillingList"
        style="width: 100%;"
      >
        <el-table-column
          prop="goodsName"
          label="商品信息"
          width="180"
        />
        <el-table-column
          prop="specAlias"
          label="规格"
          width="100"
        />
        <el-table-column
          prop="weight"
          label="重量(kg)"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.weight?scope.row.weight.toFixed(2):'0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="gPrice"
          label="商品单价(元)"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.gPrice?scope.row.gPrice.toFixed(2):'0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsCount"
          label="数量(瓶)"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.goodsCount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="gPrefPrice"
          label="优惠金额(元)"
          width="100"
        >
          <template slot-scope="scope">
            <el-input-number v-if="scope.row.isEdit" v-model="scope.row.gPrefPrice" :precision="2" :controls="false" @blur="countPriceChange(scope.row,scope.$index)" />
            <span v-else>{{ scope.row.gPrefPrice?scope.row.gPrefPrice:'0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalPrice "
          label="总金额(元)"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.totalPrice ?Number(scope.row.totalPrice).toFixed(2):'0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editClick(scope.row,scope.$index,)">{{ scope.row.isEdit?'保存':'编辑' }}</el-button>
            <!-- <el-button class="del" type="text" size="small" @click="delClick(scope.row,scope.$index,)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="tips">（优惠金额支持输入负数，正数表示下调，负数表示上调）</div>

      <div class="btn-b">
        <el-button type="default" @click="cancel">取消</el-button>
        <el-button type="primary" :loading="$loadingPlugin.save" @click="save">保存</el-button>
        <el-button type="primary" :loading="$loadingPlugin.saveAndPrint" @click="saveAndPrint">保存并打印</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import { fillingSave, getfillingDetail, invenPPDetail } from '@/api'
  import { getSummaries } from '../js/summary'
  export default {
    name: 'pingpiImport',
    props: {
      fillingLabelList: {
        type: Array,
        default: () => []
      },
      customerTypeMap: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        form: {
          invenBillCode: ''
        },
        fillingLabel: '',
        fillingData: [],
        fillingInfo: {},
        visible: false
      }
    },
    methods: {
      formatColumnMap,
      getSummaries,
      open(row) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (row) {
            this.fillingInfo = JSON.parse(JSON.stringify(row))
            this.form.invenBillCode = this.fillingInfo.invenBillCode
            this.getInvenPPDetail(this.fillingInfo.invenBillCode)
          }
        })
      },
      onSubmit() {
        if (this.form.invenBillCode) {
          this.getInvenPPDetail(this.form.invenBillCode)
        } else {
          this.$message.warning('请输入或选择领瓶单')
        }
      },
      toSelecte() {
        this.visible = false
        this.$emit('pingpiTypeIn')
      },
      async getInvenPPDetail(invenBillCode) {
        const param = {
          invenBillCode
        }
        const res = await invenPPDetail(param)
        if (res && res.data) {
          this.fillingInfo = res.data
          this.fillingData = res.data.detailList.map(item => ({
            ...item,
            gPrefPrice: 0,
            isEdit: false
          }))
        }
      },
      closed() {
        this.visible = false
        this.fillingData = []
        this.fillingInfo = {}
        this.form.invenBillCode = ''
        this.fillingLabel = ''
      },
      cancel() {
        this.closed()
      },
      // 数量变化
      countPriceChange(row, idx) {
        console.log((row.gPrice * 1) * (row.goodsCount * 1) - (row.gPrefPrice * 1))
        if ((row.gPrice * 1) * (row.goodsCount * 1) >= (row.gPrefPrice * 1)) {
          this.fillingData[idx].totalPrice = ((row.gPrice * 1) * (row.goodsCount * 1) - (row.gPrefPrice * 1)).toFixed(2)
        } else {
          this.$message.warning('优惠金额不得大于商品价格')
        }
      },
      // 编辑商品
      editClick(row, idx) {
        if (row.isEdit) {
          const i = this.fillingData.find(item => (item.goodsId === row.goodsId) && (!item.isEdit))
          if (i) {
            this.$message.warning('请勿重复添加商品')
            return
          }
          if ((row.gPrice * 1) * (row.goodsCount * 1) >= (row.gPrefPrice * 1)) {
            this.fillingData[idx].isEdit = false
          } else {
            this.$message.warning('优惠金额不得大于商品价格')
          }
        } else {
          this.fillingData[idx].isEdit = true
        }
      },
      // 删除
      delClick(row, idx) {
        this.fillingData.splice(idx, 1)
      },
      getParams() {
        const params = {
          DetailList: this.fillingData.map((item) => ({
            goodsId: item.goodsId,
            goodsName: item.goodsName,
            goodsCount: item.goodsCount,
            specAliasCode: item.specAliasCode,
            specAlias: item.specAlias,
            weight: item.weight,
            gPrice: Number(item.gPrice.toFixed(2)),
            gPrefPrice: Number(item.gPrefPrice.toFixed(2)),
            totalPrice: Number(item.totalPrice)
          }))
        }
        if (this.fillingInfo.withdrawType === 2) {
          params.withdrawUser = this.fillingInfo.withdrawUser
          params.withdrawCode = this.fillingInfo.withdrawCode
          params.withdrawId = this.fillingInfo.withdrawId
          params.withdrawType	 = this.fillingInfo.withdrawType
          params.orgId = this.fillingInfo.orgId
          params.orgName = this.fillingInfo.orgName
          params.orgSNNo = this.fillingInfo.orgSNNo
          params.invenBillCode = this.fillingInfo.invenBillCode
          params.fillingLabel = this.fillingLabel
          params.fillingType = 2
        }
        return params
      },
      // 保存
      async save() {
        if (!this.fillingLabel) {
          this.$message.warning('请选择单据标签！')
          return
        }
        const noSave = this.fillingData.some(item => item.isEdit)
        if (noSave) {
          this.$message.warning('存在未保存商品')
          return
        }
        const params = await this.getParams()
        const res = await fillingSave(params)
        if (res) {
          this.$message.success('保存成功')
          this.resolve()
          this.visible = false
        }
      },
      async saveAndPrint() {
        if (!this.fillingLabel) {
          this.$message.warning('请选择单据标签！')
          return
        }
        const noSave = this.fillingData.some(item => item.isEdit)
        if (noSave) {
          this.$message.warning('存在未保存商品')
          return
        }
        const params = await this.getParams()
        const res = await fillingSave(params)
        if (res && res.data) {
          this.$message.success('保存成功')
          this.groovePrint(res.data)
        }
      },
      async groovePrint(id) {
        const params = {
          fillingId: id
        }
        const res = await getfillingDetail(params)
        if (res && res.data) {
          this.print(res.data)
        }
      },
      print(row2) {
        const row = JSON.parse(JSON.stringify(row2))
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['40']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const r = {
          fillingTotalPrice: row.fillingTotalPrice,
          fillingCode: row.fillingCode,
          printDt: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
          withdrawUser: row.withdrawUser,
          withdrawCode: row.withdrawCode,
          fillingCount: row.fillingCount,
          orgName: row.operateOrgName,
          fillingLabelName: row.fillingLabelName ? row.fillingLabelName : '',
          cardSurplus: row.cardSurplusName ? row.cardSurplusName : '',
          preferentialCount: row.preferentialCountName ? row.preferentialCountName : ''
        }
        const i = row.detailList.map((item) => ({
          goodsName: item.goodsName,
          specAlias: item.specAlias,
          weight: item.weight ? item.weight : '0',
          goodsCount: item.goodsCount
        }))

        let printcmd = {
          cmd: 2,
          title: `正在对充装单${r.fillingCode}进行打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }
        window.jCPrint.process(printcmd, temp, r, i)
        delete printcmd.els
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
          this.resolve()
          this.visible = false
        } else {
          this.$message.error('打印未连接')
        }
      }

    }
  }
</script>

<style lang="scss" scoped>
.item-title {
  margin: 10px  0;
  color: #01999F;
  &:nth-child(1) {
    margin-top: 0;
  }
  &:nth-last-of-type(1) {
    margin-bottom: 20px;
  }
}
.grid-content {
  line-height: 30px;
  .item-red {
    color: red;
  }
  .item-green {
    color: green;
  }
}
.add {
  margin: 10px 0;
}
.customerForm {
  /deep/ .el-form-item__label {
    padding: 0 6px 0 0;
  }
}
.btn-b {
  margin-top: 20px;
  text-align: right;
}
.pingpiImport {
  /deep/ .el-dialog__body {
    min-height: 300px;
  }
}
.del {
  color: red !important;
}
.fillingList {
  /deep/ .el-input-number--small {
    width: auto;
  }
}
.tips {
  margin-top: 10px;
  color: red;
}
</style>
